package richbar.com.richbar.activity.login;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.common.base.BaseActivity;
import com.common.util.LogUtil;
import com.common.util.StringUtil;
import com.common.util.ToastUtil;
import com.okhttp.network.HttpUtils;
import com.okhttp.network.MyGson;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import richbar.com.richbar.MainActivity;
import richbar.com.richbar.R;
import richbar.com.richbar.base.BaseApplication;
import richbar.com.richbar.bean.CodeBean;
import richbar.com.richbar.bean.LoginBean;
import richbar.com.richbar.help.CountDownTimerHelp;
import richbar.com.richbar.help.TitleHelp;
import richbar.com.richbar.util.LoadingDialog;
import richbar.com.richbar.util.NetWorkUtil;
import richbar.com.richbar.util.SpUtil;
import richbar.com.richbar.util.Util;

/**
 * Created by QiYang on 2018/10/15.
 */

public class LoginAc extends BaseActivity {
    public static void start(Activity activity) {
        Intent intent = new Intent(activity, LoginAc.class);
       // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    private static final String REFRESH = "com.richbar.REFRESH";
    private RefreshReceiver refreshReceiver;//点击关闭，发送广播
    @BindView(R.id.tel)
    EditText tel;
    @BindView(R.id.pwd)
    EditText pwd;
    @BindView(R.id.forget_pwd)
    TextView forgetPwd;
    @BindView(R.id.login)
    TextView login;
    @BindView(R.id.look_pwd)
    ToggleButton look_pwd;
    @BindView(R.id.identifying_code)
    TextView identifyingCode;
    @BindView(R.id.register)
    TextView register;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.l2)
    LinearLayout l2;
    @BindView(R.id.code)
    EditText code;
    @BindView(R.id.get_code)
    TextView get_code;
    private LoadingDialog dialog;
  //  private LoginBean loginBean;
    private boolean isCanLookPwd = false;
    private boolean b = true;
    private String type = "1";
    private String str_code = "";

    @Override
    public int initLayout() {
        return R.layout.ac_login;
    }

    @Override
    public void initTitle() {
        new TitleHelp(this).setTitle("").setRightTv(getString(R.string.customer_service), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "0411-87559133-804"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        registerBroad();
        setLoginBtnStyle();
        dialog = new LoadingDialog(LoginAc.this, 0);
//        loginBean = SpUtil.getLoginInfo(this);
    }

    @Override
    public void initData() {
        login();
    }

    @OnClick({R.id.forget_pwd, R.id.identifying_code, R.id.register, R.id.look_pwd, R.id.login_wx, R.id.get_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.forget_pwd:
                start(ForgetPwdAc.class);
                break;
            case R.id.identifying_code:
                if (b) {
                    identifyingCode.setText("账号密码登陆");
                    b = false;
                    ll.setVisibility(View.GONE);
                    l2.setVisibility(View.VISIBLE);
                } else {
                    identifyingCode.setText("短信验证码登陆");
                    b = true;
                    ll.setVisibility(View.VISIBLE);
                    l2.setVisibility(View.GONE);
                }
                break;
            case R.id.register:
                start(RegisterAc.class);
                break;
            case R.id.look_pwd:
                if (isCanLookPwd) {
                    look_pwd.setChecked(true);
                    pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    isCanLookPwd = false;
                } else {
                    look_pwd.setChecked(false);
                    pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    isCanLookPwd = true;
                }
                break;
            case R.id.login_wx:
                loginWx();
                break;
            case R.id.get_code:
                if (tel.getText().toString().trim().length() == 11) {
                    if (!Util.checkNet(getApplicationContext())) {
                        ToastUtil.showToast(getApplicationContext(), getString(R.string.error_net));
                    } else {
                        getCode();
                        NetWorkUtil.getRegsinCode(Util.md5(), tel.getText().toString(), "2", new HttpUtils.HttpCallback() {
                            @Override
                            public void onSuccess(String data) {
                                final CodeBean codeBean = MyGson.getInstance().fromJson(data, CodeBean.class);
                                ToastUtil.showToast(LoginAc.this, codeBean.getMsg());
                            }

                            @Override
                            public void onError(String msg) {
                                super.onError(msg);
                                ToastUtil.showToast(LoginAc.this, msg);
                            }
                        });
                    }
                    break;
                }
        }
    }

    private void getCode() {
        new CountDownTimerHelp(this, get_code, 60000, 1000).start();
    }

    private void login() {
//        if (isAuto()) {
//            BaseApplication.uid = loginBean.getData().getUid();
//            startF(MainActivity.class);
//            return;
//        }
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (b) {
                    type = "1";
                } else {
                    type = "2";
                    str_code = code.getText().toString();
                }
                if (check()) {
                    dialog.show();
                    NetWorkUtil.login(Util.md5(), type, StringUtil.getStr(tel), StringUtil.getStr(pwd), str_code, new HttpUtils.HttpCallback() {
                        @Override
                        public void onSuccess(String data) {
                            dialog.dismiss();
                            final LoginBean loginBean = MyGson.getInstance().fromJson(data, LoginBean.class);
                            if (loginBean.getData().getError().equals("0")) {
                                BaseApplication.uid = loginBean.getData().getUid();
                                SpUtil.setLoginInfo(LoginAc.this, loginBean);
                                if(BaseApplication.isLogout)
                                {
                                    BaseApplication.isLogout=false;
                                    startF(MainActivity.class);
                                }
                                else
                                    finish();
                            } else if (loginBean.getData().getError().equals("-1")) {
                                ToastUtil.showToast(getApplicationContext(), "短信验证码错误");
                            } else if (loginBean.getData().getError().equals("-2")) {
                                ToastUtil.showToast(getApplicationContext(), "用户不存在");
                            } else if (loginBean.getData().getError().equals("-3")) {
                                ToastUtil.showToast(getApplicationContext(), "用户名或密码错误");
                            }

                        }

                        @Override
                        public void onError(String msg) {
                            dialog.dismiss();
                            super.onError(msg);
                            ToastUtil.showToast(getApplicationContext(), msg);
                        }
                    });
                }
            }
        });


    }

    private void loginWx() {
        if (BaseApplication.iwxapi.isWXAppInstalled()) {
            LogUtil.e("LLLLALLLAL", "1");
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_fth";//
            req.state = "wechat_sdk_xb_live_state";
            BaseApplication.iwxapi.sendReq(req);
        } else {
            LogUtil.e("LLLLALLLAL", "2");
            ToastUtil.showToast(this, "您还没有安装微信");
        }
    }

    private void setLoginBtnStyle() {
        pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!StringUtil.isEmpty(tel.getText().toString()) && s.length() > 0) {
                    login.setBackgroundResource(R.mipmap.login_red);
                } else {
                    login.setBackgroundResource(R.mipmap.login_gray);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!StringUtil.isEmpty(tel.getText().toString()) && s.length() > 0) {
                    login.setBackgroundResource(R.mipmap.login_red);
                } else {
                    login.setBackgroundResource(R.mipmap.login_gray);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 获取账号
     *
     * @return
     */
    private String getId() {
        return tel.getText().toString().trim();
    }

    /**
     * 获取密码
     *
     * @return
     */
    private String getPwd() {
        return pwd.getText().toString().trim();
    }

    /**
     * 登录之前的检测
     *
     * @return
     */
    private boolean check() {
        if (getId().length() != 11) {
            ToastUtil.showToast(getApplicationContext(), getString(R.string.error_tel));
            return false;
        }
        if (getPwd().length() == 0 && !type.equals("2")) {
            ToastUtil.showToast(getApplicationContext(), getString(R.string.error_pwd));
            return false;
        }
        if (!Util.checkNet(getApplicationContext())) {
            ToastUtil.showToast(getApplicationContext(), getString(R.string.error_net));
            return false;
        }
        return true;
    }


//    private boolean isAuto() {
//        LogUtil.e("APPADPPADPW", loginBean);
//        if (null != loginBean) {
//            LogUtil.e("APPADPPADPW", 1);
//            return true;
//        } else {
//            LogUtil.e("APPADPPADPW", 2);
//            return false;
//        }
//    }

    private void registerBroad() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(REFRESH);
        refreshReceiver = new RefreshReceiver();
        registerReceiver(refreshReceiver, intentFilter);
    }

    public static void sendRefreshBroad(Context context) {
        Intent intent = new Intent();
        intent.setAction(REFRESH);
        context.sendBroadcast(intent);
    }


    /**
     * 刷新列表
     */
    private class RefreshReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            LoginAc.this.finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(refreshReceiver);
    }

    @Override
    public void onBackPressed() {
        if(BaseApplication.isLogout)
        {
            BaseApplication.isLogout=false;
            startF(MainActivity.class);
        }
        else
            finish();
    }
}
